/**
 * 云南电价预测
 */
import type { ProvinceType } from '@/hooks/useRequestPowerAfterInit';
import { useRequestPowerAfterInit } from '@/hooks/useRequestPowerAfterInit';
import { TjFilter, TjHeader } from '@/tjComponents';
import { PageLoading } from '@ant-design/pro-layout';
import { useRequest } from 'ahooks';
import { Button, DatePicker, Form, Row, Select } from 'antd';
import moment from 'moment';
import { useMemo, useState } from 'react';
import { query } from './service';
import Chart from './component/Chart';
import { AntdBaseTable } from './component/BaseTable';
import styles from './index.less';
import Pointer from '../ClearingPriceForecast/component/Pointer';
import { UploadOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import { exportTableData, transformResDataToChartData, transformResDataToTableData } from './utils';
import type { ClearingPriceForecast } from './type';
import ClearingPriceForecastEmpty from './component/ClearingPriceForecastEmpty';
import _ from 'lodash';

interface Props {
  province: ProvinceType[];
  defaultValues: any;
}
const Content = (props: Props) => {
  const { province, defaultValues } = props;
  const [form] = Form.useForm();
  const [stationsOptions, setStationsOptions] = useState(province?.[0]?.stations || []);
  const [conditions, setConditions] = useState<Record<any, string | undefined>>(defaultValues);
  const { data, loading } = useRequest<ClearingPriceForecast[], any>(
    async () => {
      const { date = [], ...rest } = conditions;

      const res = await query({
        ...(rest || {}),
        forecastStartTime: date?.[0] ? moment(date?.[0]).format('YYYY-MM-DD HH:mm:ss') : undefined,
        forecastEndTime: date?.[1]
          ? moment(date?.[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
          : undefined,
      });
      return res.data || [];
    },
    {
      ready: !!conditions,
      refreshDeps: [conditions],
    },
  );

  const filterItems = useMemo(
    () => [
      {
        name: 'marketId',
        render: (
          <Select
            options={province}
            style={{ width: 180 }}
            onChange={(_, row) => {
              setStationsOptions(row?.stations || []);
              form.setFieldsValue({
                stationIds: [],
              });
            }}
            placeholder="请选择"
          />
        ),
      },
      {
        name: 'stationIds',
        render: (
          <Select
            maxTagCount="responsive"
            mode="multiple"
            style={{ width: 180 }}
            placeholder="请选择"
            options={stationsOptions?.map((item) => ({
              label: item.stationName,
              value: item.stationId,
            }))}
          />
        ),
      },
      {
        name: 'date',
        render: <DatePicker.RangePicker picker="date" placeholder={['开始时间', '结束时间']} />,
      },
      {
        name: 'timePoint',
        render: (
          <Pointer
            options={[
              { label: 24, value: 24 },
              { label: 96, value: 96 },
            ]}
          />
        ),
      },
    ],
    [stationsOptions, province, setStationsOptions, form],
  );
  const chart = transformResDataToChartData(data!);
  const table = transformResDataToTableData(data!);
  return (
    <>
      <TjHeader
        left={
          <TjFilter
            loading={loading}
            form={form}
            defaultValues={defaultValues}
            items={filterItems}
            onSearch={(params) => {
              setConditions(params);
            }}
            onReset={(params) => setConditions(params || defaultValues)}
          />
        }
      />
      <div className={styles.wrapper}>
        {loading ? (
          <PageLoading />
        ) : (
          <>
            <Row justify="space-between" className={styles.box}>
              <div className={styles.title}>电价预测</div>
              <Button type="link" icon={<UploadOutlined />} onClick={() => exportTableData(table)}>
                导出
              </Button>
            </Row>

            <ClearingPriceForecastEmpty isEmpty={_.isEmpty(data)}>
              <Chart
                yAxisName="元/kWh"
                className={styles.box}
                xAxisData={chart.xisx}
                series={[
                  { data: chart.dayAheadClearingPriceForecast, name: '日前电价预测' },
                  { data: chart.realTimeClearingPriceForecast, name: '实时电价预测' },
                ]}
              />
              <AntdBaseTable isLoading={loading} primaryKey="type" {...table} useVirtual="auto" />
            </ClearingPriceForecastEmpty>
          </>
        )}
      </div>
    </>
  );
};

function PredictElectricityPrice(props: { menuCode: string }) {
  const { initLoading, province } = useRequestPowerAfterInit(
    `/power/dataPower/common/${props.menuCode}/t_station`,
    () => {},
    {
      convertResult: '1',
    },
  );

  return initLoading ? (
    <PageLoading />
  ) : (
    <>
      <Content
        province={province}
        defaultValues={{
          date: [moment().startOf('week'), moment().endOf('week')],
          timePoint: 24,
          marketId: province?.[0]?.value,
          stationIds: province?.[0]?.stations?.[0]?.stationId
            ? [province?.[0]?.stations?.[0]?.stationId]
            : [],
        }}
      />
    </>
  );
}

export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
}))(PredictElectricityPrice);
